package com.ocean.stack;

import java.util.*;

/**
 * https://leetcode.cn/problems/next-greater-element-i/
 */
public class NextGreaterElementI2 {
    public static void main(String[] args) {
        // nums1 = [4,1,2], nums2 = [1,3,4,2].
        // nums1 = [2,4], nums2 = [1,2,3,4].
        int[] nums1 = {2, 4};
        int[] nums2 = {1, 2, 3, 4};
        NextGreaterElementI2 greaterElementI = new NextGreaterElementI2();
        int[] ints = greaterElementI.nextGreaterElement2(nums1, nums2);
        System.out.println(Arrays.toString(ints));
//        int[] ints1 = greaterElementI.nextGreaterElement2(nums1, nums2);
//        System.out.println(Arrays.toString(ints1));

    }

    /**
     * 暴力求解
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        int[] res = new int[nums1.length];
        int l1 = nums1.length;
        int l2 = nums2.length;
        for (int i = 0; i < l1; i++) {
            int item = nums1[i];
            // 先找到相等的节点
            int k = 0;
            while (k <= l2 - 1 && item != nums2[k]) {
                k++;
            }
            // 找到下一个大的
            while (k <= l2 - 1 && nums2[k] <= item) {
                k++;
            }
            // 找到了 或者是k<0
            res[i] = k >= l2 ? -1 : nums2[k];
        }
        return res;
    }

    /**
     * 变量num2  将下一个大的先存下来
     * 2 4
     * 1 2 3 4
     * <p>
     * 4
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] nextGreaterElement2(int[] nums1, int[] nums2) {
        Deque<Integer> stack = new LinkedList<>();
        Map<Integer, Integer> map = new HashMap<>();
        int l2 = nums2.length;
        for (int i = l2 - 1; i >= 0; i--) {
            int item = nums2[i];
            while (!stack.isEmpty() && stack.peek() < item) {
                stack.pop();
            }
            map.put(item, stack.isEmpty() ? -1 : stack.peek());
            stack.push(item);
        }
        int[] res = new int[nums1.length];
        for (int i = 0; i < nums1.length; i++) {
            res[i] = map.get(nums1[i]);
        }
        return res;
    }
}
